﻿using ExcelUnity.Exporter.Exporters;
using System.Collections.Generic;
using System.Linq;

namespace ExcelUnity.Exporter.Wrappers.SheetWrapperBuilders
{
    public abstract class BaseBuilder
    {
        public ExportSheetWrapper? BuildExportSheetWrapper(ExportSheet exportSheet)
        {
            var columnAdapters = BuildColumnAdapter(exportSheet);
            if (columnAdapters == null) return null;

            foreach (var adapter in columnAdapters)
            {
                if (adapter.MergedRowAlone == true)
                    adapter.MergedRowByPrimaryKey = false;
            }

            var exportRows = new List<ExportRowWrapper>();

            //创建title
            var rowIndex = exportSheet.StartRowIndex ?? 0;
            if (exportSheet.Title != null)
            {
                var cells = columnAdapters.Select(x => new ExportCellWrapper(x.ColumnIndex,
                                                                x.ColumnIndex == 0 ? exportSheet.Title.Title : string.Empty,
                                                                exportSheet.Title.Style)
                {
                    MergeColumn = true,
                }).ToList();
                var row = new ExportRowWrapper(cells, rowIndex++);
                exportRows.Add(row);
            }

            //创建header
            exportRows.Add(new ExportRowWrapper(columnAdapters.Select(x => new ExportCellWrapper(x.ColumnIndex, x.Name, x.HeaderStyle)).ToList(), rowIndex++));

            //填充行
            var addRows = FillDataRows(exportSheet, columnAdapters, rowIndex).ToList();
            exportRows.AddRange(addRows);
            rowIndex += addRows.Count;

            var columns = columnAdapters.Select(x => new ExportColumnWrapper(x.ColumnIndex, x.Name)
            {
                MinWidth = x.MinWidth,
                MaxWidth = x.MaxWidth
            }).ToList();
            return new ExportSheetWrapper(columns, exportRows, exportSheet.WaterMark);
        }
        public abstract List<ColumnAdapter> BuildColumnAdapter(ExportSheet sheet);

        public abstract IEnumerable<ExportRowWrapper> FillDataRows(ExportSheet sheet, List<ColumnAdapter> columnAdapters, int rowIndex);
    }
}
